/**
 * 智慧小区管理系统 - 用户API接口
 * @author Wu.Liang
 * @date 2024-01-01
 * @updated 2024-12-21 - 完善用户管理API接口
 */
import api from './request'

const USER_PATH_PREFIX = '/api/user'

// 用户接口类型定义
export interface LoginForm {
    username: string
    password: string
    captcha?: string
}

export interface UserInfo {
    id: number
    username: string
    nickname: string
    avatar?: string
    email?: string
    phone?: string
    realName?: string
    userType?: number
    status: number
    createTime: string
    updateTime: string
    roles: string[]
    permissions: string[]
    propertyCompanyId?: number | string
}

export interface RegisterForm {
    username: string
    password: string
    realName: string
    phone: string
    email: string
    communityId: number
    building: string
    room: string
}

// 用户列表查询参数
export interface UserListParams {
    current: number
    size: number
    username?: string | undefined
    realName?: string | undefined
    phone?: string | undefined
    email?: string | undefined
    status?: number | undefined
    userType?: number | undefined
    sortField?: string | undefined
    sortOrder?: string | undefined
}

// 用户列表响应
export interface UserListResponse {
    records: UserInfo[]
    total: number
    current: number
    size: number
}

// 用户表单数据
export interface UserFormData {
    id?: number
    username: string
    password?: string
    realName: string
    nickname?: string
    phone: string
    email?: string
    userType: number
    status?: number
    regionId?: number
    communityId?: number
    remark?: string
}

// 登录请求接口 - 与后端LoginDTO完全匹配
export interface LoginRequest {
    username: string
    password: string
    captcha?: string
    captchaKey?: string
    rememberMe?: boolean
    loginIp?: string
}

// 登录响应接口 - 与后端LoginVO完全匹配
export interface LoginResponse {
    token: string
    refreshToken?: string
    expireIn: number
    userId: number
    username: string
    realName?: string
    nickname: string
    avatar?: string
    userType?: number
    userTypeName?: string
    roles: string[]
    permissions: string[]
    menuPermissions: string[]
    lastLoginTime?: string
    lastLoginIp?: string
}

// 用户权限信息响应
export interface UserAuthInfo {
    userInfo: UserInfo
    roles: string[]
    permissions: string[]
    routes: unknown[]
}

// 验证码响应数据 - 与后端接口匹配
export interface CaptchaResponse {
    captchaKey: string
    captcha: string
    expireIn: number
}

// 登录日志接口
export interface LoginLog {
    id: number
    userId: number
    username: string
    loginIp?: string
    loginAddress?: string
    browser?: string
    os?: string
    deviceType?: number
    loginType?: number
    loginStatus: number
    loginMessage?: string
    loginTime: string
    logoutTime?: string
    onlineDuration?: number
    createTime: string
    updateTime: string
}

/**
 * 用户登录 - 与后端AuthController.login接口匹配
 * @param data 登录请求数据
 * @returns 登录响应结果
 */
export const login = (data: LoginRequest): Promise<{ data: LoginResponse }> => {
    return api.post(USER_PATH_PREFIX + '/auth/login', data)
}

/**
 * 用户退出登录 - 与后端AuthController.logout接口匹配
 * @returns 登出结果
 */
export const logout = (): Promise<any> => {
    return api.post(USER_PATH_PREFIX + '/auth/logout')
}

/**
 * 获取用户信息和权限 - 与后端AuthController.getCurrentUser接口匹配
 * @returns 用户信息
 */
export const getInfo = (): Promise<{ data: LoginResponse }> => {
    return api.get(USER_PATH_PREFIX + '/auth/info')
}

/**
 * 刷新Token - 与后端AuthController.refreshToken接口匹配
 * @param refreshToken 刷新令牌
 * @returns 新的Token信息
 */
export const refreshToken = (refreshToken: string): Promise<{ data: { accessToken: string; refreshToken: string } }> => {
    return api.post(USER_PATH_PREFIX + '/auth/refresh', { refreshToken })
}

/**
 * 获取当前用户信息 - 与后端AuthController.getCurrentUser接口匹配
 * @returns 用户信息
 */
export const getCurrentUser = (): Promise<{ data: UserInfo }> => {
    return api.get(USER_PATH_PREFIX + '/auth/info')
}

/**
 * 获取用户菜单 - 与后端AuthController.getUserMenus接口匹配
 * @returns 用户菜单列表
 */
export const getUserMenus = (): Promise<{ data: any[] }> => {
    return api.get(USER_PATH_PREFIX + '/auth/menus')
}

/**
 * 更新用户信息 - 与后端UserController.updateUser接口匹配
 * @param userId 用户ID
 * @param data 用户信息
 * @returns 更新结果
 */
export const updateProfile = (userId: number, data: Partial<UserInfo>): Promise<{ data: UserInfo }> => {
    // 后端接口是@PutMapping，没有路径参数，用户ID在请求体中
    const updateData = { ...data, id: userId }
    return api.put(`${USER_PATH_PREFIX}`, updateData)
}

/**
 * 获取用户详情 - 与后端UserController.getUserById接口匹配
 * @param userId 用户ID
 * @returns 用户详情
 */
export const getUserById = (userId: number): Promise<{ data: UserInfo }> => {
    return api.get(`${USER_PATH_PREFIX}/detail/${userId}`)
}

/**
 * 更新当前用户个人资料 - 与后端UserController.updateCurrentUserProfile接口匹配
 * @param data 用户信息
 * @returns 更新结果
 */
export const updateCurrentUserProfile = (data: {
    realName?: string
    nickname?: string
    phone?: string
    email?: string
    avatar?: string
}): Promise<{ data: UserInfo }> => {
    return api.put(`${USER_PATH_PREFIX}/users/profile/update`, data)
}

/**
 * 修改密码 - 与后端AuthController.changePassword接口匹配
 * @param data 修改密码参数
 * @returns 修改结果
 */
export const changePassword = (data: {
    oldPassword: string
    newPassword: string
    userId: number
}): Promise<any> => {
    return api.post(USER_PATH_PREFIX + '/auth/password/change', data)
}

/**
 * 上传头像 - 与后端FileController接口匹配
 * @param file 头像文件
 * @returns 上传结果
 */
export const uploadAvatar = (file: File): Promise<{ data: { url: string } }> => {
    const formData = new FormData()
    formData.append('file', file)
    return api.post(USER_PATH_PREFIX + '/file/upload', formData, {
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    })
}

/**
 * 获取验证码图片 - 与后端AuthController.generateCaptcha接口匹配
 * @returns 验证码信息
 */
export const getCaptchaImage = (): Promise<{ data: CaptchaResponse }> => {
    return api.get(USER_PATH_PREFIX + '/auth/captcha/image')
}

/**
 * 刷新验证码 - 与后端AuthController.generateCaptcha接口匹配
 * @param captchaKey 验证码key
 * @returns 新的验证码信息
 */
export const refreshCaptcha = (captchaKey: string): Promise<{ data: CaptchaResponse }> => {
    return api.get(USER_PATH_PREFIX + '/auth/captcha/image')
}

/**
 * 发送短信验证码 - 与后端AuthController.sendSmsCaptcha接口匹配
 * @param data 短信参数
 * @returns 发送结果
 */
export const sendSmsCode = (data: {
    phone: string
    businessType: number
    captcha?: string
    captchaKey?: string
}): Promise<any> => {
    return api.post(USER_PATH_PREFIX + '/auth/captcha/sms', data)
}

/**
 * 发送邮箱验证码 - 与后端AuthController.sendEmailCaptcha接口匹配
 * @param data 邮箱参数
 * @returns 发送结果
 */
export const sendEmailCaptcha = (data: {
    email: string
    businessType: number
}): Promise<any> => {
    return api.post(USER_PATH_PREFIX + '/auth/captcha/email', data)
}

/**
 * 重置密码 - 与后端AuthController.resetPassword接口匹配
 * @param data 重置密码参数
 * @returns 重置结果
 */
export const resetPassword = (data: {
    target: string
    code: string
    newPassword: string
}): Promise<any> => {
    return api.post(USER_PATH_PREFIX + '/auth/password/reset', data)
}

/**
 * 用户注册 - 与后端AuthController.register接口匹配
 * @param data 注册数据
 * @returns 注册结果
 */
export const register = (data: RegisterForm): Promise<{ data: LoginResponse }> => {
    return api.post(USER_PATH_PREFIX + '/auth/register', data)
}

/**
 * 获取用户信息 - 与后端AuthController.getCurrentUser接口匹配
 * @returns 用户信息
 */
export const getUserInfo = (): Promise<{ data: UserInfo }> => {
    return api.get(USER_PATH_PREFIX + '/auth/info')
}

/**
 * 获取用户列表 - 与后端UserController.getUserList接口匹配
 * @param params 查询参数
 * @returns 用户列表
 */
export const getUserList = (params: UserListParams): Promise<{ data: UserListResponse }> => {
    return api.get(USER_PATH_PREFIX + '/list', { params })
}

/**
 * 获取用户详情
 * @param id 用户ID
 * @returns 用户详情
 */
export const getUserDetail = (id: number): Promise<{ data: UserInfo }> => {
    return api.get(`${USER_PATH_PREFIX}/detail/${id}`)
}

/**
 * 创建用户 - 与后端UserController.createUser接口匹配
 * @param data 用户数据
 * @returns 创建结果
 */
export const createUser = (data: UserFormData): Promise<{ data: UserInfo }> => {
    return api.post(USER_PATH_PREFIX, data)
}

/**
 * 更新用户 - 与后端UserController.updateUser接口匹配
 * @param id 用户ID
 * @param data 用户数据
 * @returns 更新结果
 */
export const updateUser = (id: number, data: Partial<UserFormData>): Promise<{ data: UserInfo }> => {
    return api.put(USER_PATH_PREFIX, data)
}

/**
 * 删除用户 - 与后端UserController.deleteUser接口匹配
 * @param id 用户ID
 * @returns 删除结果
 */
export const deleteUser = (id: number): Promise<any> => {
    return api.delete(`${USER_PATH_PREFIX}/delete/${id}`)
}

/**
 * 批量删除用户 - 与后端UserController.batchDeleteUsers接口匹配
 * @param userIds 用户ID数组
 * @returns 删除结果
 */
export const batchDeleteUsers = (userIds: number[]): Promise<any> => {
    return api.delete(USER_PATH_PREFIX + '/batch', { data: userIds })
}

/**
 * 更新用户状态 - 与后端UserController.updateUserStatus接口匹配
 * @param id 用户ID
 * @param status 状态
 * @returns 更新结果
 */
export const updateUserStatus = (id: number, status: number): Promise<any> => {
    if (status === 1) {
        return api.post(`${USER_PATH_PREFIX}/status/enable/${id}`)
    } else if (status === 0) {
        return api.post(`${USER_PATH_PREFIX}/status/disable/${id}`)
    } else {
        return Promise.reject(new Error('无效的状态值'))
    }
}

/**
 * 重置用户密码 - 与后端UserController.resetPassword接口匹配
 * @param id 用户ID
 * @returns 重置结果
 */
export const resetUserPassword = (id: number): Promise<any> => {
    return api.post(`${USER_PATH_PREFIX}/password/reset/${id}`)
}

/**
 * 获取用户角色 - 与后端UserController.getUserRoles接口匹配
 * @param id 用户ID
 * @returns 角色列表
 */
export const getUserRoles = (id: number): Promise<{ data: string[] }> => {
    return api.get(`${USER_PATH_PREFIX}/role/list/${id}`)
}

/**
 * 检查用户名唯一性 - 与后端UserController.checkUsernameUnique接口匹配
 * @param username 用户名
 * @param excludeUserId 排除的用户ID
 * @returns 检查结果
 */
export const checkUsernameUnique = (username: string, excludeUserId?: number): Promise<{ data: boolean }> => {
    let url = `${USER_PATH_PREFIX}/check/username?username=${username}`
    if (excludeUserId) {
        url += `&excludeUserId=${excludeUserId}`
    }
    return api.get(url)
}

/**
 * 检查手机号唯一性 - 与后端UserController.checkPhoneUnique接口匹配
 * @param phone 手机号
 * @param excludeUserId 排除的用户ID
 * @returns 检查结果
 */
export const checkPhoneUnique = (phone: string, excludeUserId?: number): Promise<{ data: boolean }> => {
    let url = `${USER_PATH_PREFIX}/check/phone?phone=${phone}`
    if (excludeUserId) {
        url += `&excludeUserId=${excludeUserId}`
    }
    return api.get(url)
}

/**
 * 检查邮箱唯一性 - 与后端UserController.checkEmailUnique接口匹配
 * @param email 邮箱
 * @param excludeUserId 排除的用户ID
 * @returns 检查结果
 */
export const checkEmailUnique = (email: string, excludeUserId?: number): Promise<{ data: boolean }> => {
    let url = `${USER_PATH_PREFIX}/check/email?email=${email}`
    if (excludeUserId) {
        url += `&excludeUserId=${excludeUserId}`
    }
    return api.get(url)
}

/**
 * 检查身份证号唯一性 - 与后端UserController.checkIdCardUnique接口匹配
 * @param idCard 身份证号
 * @param excludeUserId 排除的用户ID
 * @returns 检查结果
 */
export const checkIdCardUnique = (idCard: string, excludeUserId?: number): Promise<{ data: boolean }> => {
    let url = `${USER_PATH_PREFIX}/check/idcard?idCard=${idCard}`
    if (excludeUserId) {
        url += `&excludeUserId=${excludeUserId}`
    }
    return api.get(url)
}

/**
 * 手机号登录 - 与后端AuthController.phoneLogin接口匹配
 * @param data 登录参数
 * @returns 登录结果
 */
export const phoneLogin = (data: {
    phone: string
    code: string
}): Promise<{ data: LoginResponse }> => {
    return api.post(USER_PATH_PREFIX + '/auth/phone-login', data)
}

/**
 * 微信登录 - 与后端AuthController.wechatLogin接口匹配
 * @param data 登录参数
 * @returns 登录结果
 */
export const wechatLogin = (data: {
    code: string
    state?: string
}): Promise<{ data: LoginResponse }> => {
    return api.post(USER_PATH_PREFIX + '/auth/wechat-login', data)
}

/**
 * 获取微信二维码 - 与后端AuthController.getWechatQrCode接口匹配
 * @returns 二维码信息
 */
export const getWechatQrCode = (): Promise<{ data: { qrCode: string; state: string } }> => {
    return api.get(USER_PATH_PREFIX + '/auth/wechat-qrcode')
}

/**
 * 检查微信登录状态 - 与后端AuthController.checkWechatLoginStatus接口匹配
 * @param state 状态参数
 * @returns 登录状态
 */
export const checkWechatLoginStatus = (state: string): Promise<{ data: { status: string; userInfo?: LoginResponse } }> => {
    return api.get(`${USER_PATH_PREFIX}/auth/wechat-status?state=${state}`)
}

/**
 * 检查登录状态 - 与后端AuthController.checkLoginStatus接口匹配
 * @returns 登录状态
 */
export const checkLogin = (): Promise<{ data: boolean }> => {
    return api.get(USER_PATH_PREFIX + '/auth/check')
}

/**
 * 获取用户权限 - 与后端UserController.getUserPermissions接口匹配
 * @returns 权限列表
 */
export const getUserPermissions = (): Promise<{ data: any[] }> => {
    return api.get(USER_PATH_PREFIX + '/permissions')
}

/**
 * 获取用户角色分配信息 - 与后端UserController.getUserRoleAssignInfo接口匹配
 * @param userId 用户ID
 * @returns 角色分配信息
 */
export const getUserRoleAssignInfo = (userId: number): Promise<{ data: any }> => {
    return api.get(`${USER_PATH_PREFIX}/role/assign/${userId}`)
}

/**
 * 分配用户角色 - 与后端UserController.assignUserRoles接口匹配
 * @param userId 用户ID
 * @param roleIds 角色ID数组
 * @returns 分配结果
 */
export const assignUserRoles = (userId: number, roleIds: number[]): Promise<any> => {
    return api.post(`${USER_PATH_PREFIX}/role/assign/${userId}`, roleIds)
}

/**
 * 获取用户登录历史 - 与后端UserController.getUserLoginHistory接口匹配
 * @param userId 用户ID
 * @param limit 限制数量
 * @returns 登录历史
 */
export const getUserLoginHistory = (userId: number, limit: number = 5): Promise<{ data: LoginLog[] }> => {
    return api.get(`${USER_PATH_PREFIX}/login/history/${userId}?limit=${limit}`)
}

// 数据权限管理API - 新增数据权限控制接口
export const dataScopeApi = {
  // 获取当前用户数据权限信息
  getDataScopeInfo: () => {
    return api.get<{
      code: number
      data: {
        userId: number
        dataScopeType: number
        communityIds: number[]
        propertyCompanyIds: number[]
        restrictions: string
        isSuperAdmin: boolean
        scopeDescription: string
      }
    }>('/api/property/data-scope/current-user')
  },

  // 检查用户是否有指定小区权限
  checkCommunityPermission: (communityId: number) => {
    return api.get<{
      code: number
      data: { hasPermission: boolean }
    }>(`/api/property/data-scope/community/${communityId}/check`)
  },

  // 批量检查用户小区权限
  batchCheckCommunityPermissions: (communityIds: number[]) => {
    return api.post<{
      code: number
      data: { authorizedCommunityIds: number[] }
    }>('/api/property/data-scope/community/batch-check', {
      communityIds
    })
  },

  // 获取用户可访问的小区列表
  getUserCommunities: () => {
    return api.get<{
      code: number
      data: number[]
    }>('/api/property/data-scope/user-communities')
  },

  // 刷新用户权限缓存
  refreshUserPermissionCache: () => {
    return api.post<{
      code: number
      data: { success: boolean }
    }>('/api/property/data-scope/refresh-cache')
  },

  // 清除用户权限缓存
  clearUserPermissionCache: (userId?: number) => {
    return api.delete<{
      code: number
      data: { success: boolean }
    }>('/api/property/data-scope/clear-cache', {
      params: { userId }
    })
  }
}

// 在现有的user.ts文件中添加上传文件相关的API方法

/**
 * 上传文件
 * @param file 文件对象
 * @param uploadType 上传类型
 * @param uploadSource 上传来源
 * @returns 上传结果
 */
export function uploadFile(file: File, uploadType: string, uploadSource: string = 'WEB') {
  const formData = new FormData()
  formData.append('file', file)
  formData.append('uploadType', uploadType)
  formData.append('uploadSource', uploadSource)
  
  return api.upload('/api/user/upload', formData)
}

/**
 * 获取文件信息
 * @param fileId 文件ID
 * @returns 文件信息
 */
export function getFileInfo(fileId: number) {
  return api.get(`/api/user/file/${fileId}`)
}

/**
 * 删除文件
 * @param fileId 文件ID
 * @returns 删除结果
 */
export function deleteFile(fileId: number) {
  return api.delete(`/api/user/file/${fileId}`)
}

/**
 * 获取用户文件列表
 * @param uploadType 上传类型（可选）
 * @returns 文件列表
 */
export function getUserFiles(uploadType?: string) {
  const params: any = {}
  if (uploadType) {
    params.uploadType = uploadType
  }
  
  return api.get('/api/user/files', { params })
}

// 系统日志相关接口
export interface SystemLogQueryParams {
    current: number
    size: number
    username?: string
    operationType?: string
    module?: string
    startTime?: string
    endTime?: string
    ipAddress?: string
    logLevel?: number
    logType?: number
    userType?: string
}

export interface SystemLog {
    id: number
    logLevel: number
    logTitle: string
    logType: number
    moduleName: string
    operationName: string
    operationDesc: string
    requestUrl: string
    requestMethod: string
    requestParams: string
    responseData: string
    responseResult: string
    userId: number
    username: string
    userType: string
    ipAddress: string
    userAgent: string
    executionTime: number
    errorMessage: string
    stackTrace: string
    logTime: string
    status: number
    createTime: string
    logContent: string
    operator: string
    operationTime: string
    createBy: number
}

export interface SystemLogResponse {
    records: SystemLog[]
    total: number
    current: number
    size: number
}

// 获取系统日志列表
export function getSystemLogList(params: SystemLogQueryParams): Promise<{ data: SystemLogResponse }> {
    return api.get(`${USER_PATH_PREFIX}/system-logs`, { params })
}

// 导出系统日志
export function exportSystemLog(params: SystemLogQueryParams): Promise<{ data: string }> {
    return api.post(`${USER_PATH_PREFIX}/system-logs/export`, null, { params })
}

// 清空系统日志
export function clearSystemLog(): Promise<any> {
    return api.delete(`${USER_PATH_PREFIX}/system-logs/clear`)
}

// 登录日志相关接口
export interface LoginLogQueryParams {
    current: number
    size: number
    username?: string
    loginStatus?: number
    loginIp?: string
    loginAddress?: string
    browser?: string
    os?: string
    deviceType?: number
    loginType?: number
    startTime?: string
    endTime?: string
    userType?: string
    propertyCompanyId?: number
}

export interface LoginLogResponse {
    records: LoginLog[]
    total: number
    current: number
    size: number
}

// 获取登录日志列表
export function getLoginLogList(params: LoginLogQueryParams): Promise<{ data: LoginLogResponse }> {
    return api.get(`${USER_PATH_PREFIX}/login-logs`, { params })
}

// 导出登录日志
export function exportLoginLog(params: LoginLogQueryParams): Promise<{ data: string }> {
    return api.post(`${USER_PATH_PREFIX}/login-logs/export`, null, { params })
}

// 清空登录日志
export function clearLoginLog(): Promise<any> {
    return api.delete(`${USER_PATH_PREFIX}/login-logs/clear`)
}
